require 'net/http'
require 'uri'
require 'iconv'

module Provider

  class MBudgetCH < AbstractProvider

    @sms_sender

    @login_name
    @password
    
    def initialize(sms_sender)
      @sms_sender = sms_sender
      @login_name = @sms_sender.get_main.login_name
      @password = @sms_sender.get_main.password
    end

    def send(to, text)
      trans =Iconv.new('ISO-8859-1','UTF-8') # new converter-object encoding from UTF-8 to ISO-8859-1
      text=URI.escape(trans.iconv(text)) # convert message to ISO-8859-1 and escape it for use in URL

      data=Net::HTTP.get(URI.parse("http://www.company.ecall.ch/ecompurl/ECOMPURL.ASP?wci=Interface&Function=SendPage&Address=#{to}&Message=#{text}&LinkID=mbudget&UserName=#{@login_name}&UserPassword=#{@password}"))

      begin
        parse_message(data)
        sms_sent
      rescue InvalidPasswordOrUsernameException => ex
        raise ex
      rescue InvalidRecipientNumberException=> ex
        raise ex
      rescue MessageHasNoCharactersException=> ex
        raise ex
      rescue UnknownSmsException=> ex
        raise ex
      end
    end

    def sms_left #returns number of sms left to send for account
      data=Net::HTTP.get(URI.parse("http://www.company.ecall.ch/ecompurl/ECOMPURL.ASP?wci=Interface&Function=GetInfoSend&LinkID=mbudget&UserName=#{@login_name}&UserPassword=#{@password}"))

      begin
        parse_message(data)
      rescue InvalidPasswordOrUsernameException => ex
        raise ex
      rescue UnknownSmsException => ex
        raise ex
      end

      # data should look like this: "ResultPage ResultCode:0 ResultText:OK JobCount:2 FreeMsgText: M-Budget Mobile SMS: nur 10 Rp! "
      # we need to extract the number after "JobCount:", that's the number of sms we have left...

      keyword="JobCount"
      keyword_index=data.index(keyword)+2
      data[keyword_index+keyword.length-1..(keyword_index+keyword.length)].to_i
    end
    
    private
    def parse_message(data)
      if data.eql?("ResultPage\tResultCode:0\tResultText:OK\r\n")
        true
      else # an error occured
        if data.eql?("ResultPage	ResultCode:11300	ResultText:AccNoUser")
          raise InvalidPasswordOrUsernameException

        elsif data.eql?("ResultPage\tResultCode:11100\tResultText:AdrAdCInvalid\r\n")
          raise InvalidRecipientNumberException

        elsif data.eql?("ResultPage\tResultCode:11200\tResultText:MsgNoCharacters\r\n")
          raise MessageHasNoCharactersException

        else
          SmsWidget::Main.logger.debug "Error msg: #{data}"
          raise UnknownSmsException
          
        end
      end
    end
    
    def sms_sent()
      @sms_sender.sms_sent
    end

    def sms_not_sent(reason)
      @sms_sender.sms_not_sent(reason)
    end
    
  end
    
end
